<?php

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 订单
 */
class Order Extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    protected static function init(){
        self::afterInsert(function ($row){

            Db::name('goods')->where(['id' => $row['goods_id']])->update(['changes_num' => $row['goods_num']]);
            User::score('-'.$row['account'],$row['user_id'],'购买商机');

        });
    }

    public static function getOrderByGoodsId($goodsId){
        $data = Db::name('order')
            ->field('u.nickname,o.createtime,o.goods_num')
            ->alias('o')
            ->join('user u','o.user_id = u.id','left')
            ->where('o.goods_id',$goodsId)
            ->select();

        return $data;
    }

    public static function isUserBuy($user_id,$goods_id){
        $result = Db::name('order')->where(['user_id' => $user_id, 'goods_id' => $goods_id])->find();
        empty($result) ? $return = 0  : $return = 1;
        return $return;
    }


}